package middlewares

import (
	"fmt"

	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/gin-gonic/gin"
)

func IsolationMiddleware(ctx *gin.Context) {
	e, b := sentinel.Entry("request-isolation", sentinel.WithBatchCount(1))
	if b != nil {
		fmt.Println("[Isolation] Blocked", "reason", b.BlockType().String(), "rule", b.TriggeredRule(), "snapshot", b.TriggeredValue())
		ctx.JSON(400, gin.H{
			"msg": "并发量太大",
		})
		// 终止程序
		ctx.Abort()
		return
	}

	e.Exit()

	ctx.Next()
}
